/**
 * 项目名称（软件名称）：忠旺机械物资管理系统(mms)
 * 研发设计单位：忠旺机械设备制造有限公司机械设计院智能控制设计科设计与研发。
 * 版权所有：忠旺机械设备制造有限公司
 * 注：本项目的一切技术专利，使用规范归解释权由忠旺机械设备制造有限公司所有。
 * 软件版本：Ver 1.0.0
 * 文件路径：com.zhongwang.mms.module.purchase.excelListener
 * 创建时间：2020年04月28日 12时56分
 **/
package com.zhongwang.mms.module.purchase.excelListener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.zhongwang.mms.base.BaseService;
import com.zhongwang.mms.common.ImportCallBack;
import com.zhongwang.mms.gen.entity.PChangeOrder;
import com.zhongwang.mms.gen.entity.PInventory;
import com.zhongwang.mms.gen.entity.PInventoryProjectMark;
import com.zhongwang.mms.module.basic.dao.BoardDao;
import com.zhongwang.mms.module.basic.dao.TProjectDao;
import com.zhongwang.mms.module.basic.dao.TWarehouseInfoDao;
import com.zhongwang.mms.module.basic.model.TProjectModel;
import com.zhongwang.mms.module.basic.service.BoardService;
import com.zhongwang.mms.module.purchase.dao.PurChangeDao;
import com.zhongwang.mms.module.purchase.dao.PurInvProDao;
import com.zhongwang.mms.module.purchase.dao.PurPInventoryDao;
import com.zhongwang.mms.module.purchase.model.*;
import com.zhongwang.mms.module.system.log.LogService;
import com.zhongwang.mms.util.BigDecimalUtils;
import com.zhongwang.mms.util.ShiroUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static com.zhongwang.mms.config.timingtask.StatisticalTimingTask.getVWProjectByCode;

/**
 * @ClassName： PChangeOrderListener
 * @Description： 批量库存划项目标记导入 Listenter
 * @Author： 徐一贺
 * @Date： 2020年6月15日14:44:50
 * @Version： V1.0
 **/
public class PInvProListener extends AnalysisEventListener<PChangeOrderExcelModel> {
    private PurInvProDao purInvProDao;
    private PurChangeDao purChangeDao;
    private BoardDao boardDao;
    private LogService logService;
    private ImportCallBack callBack;
    private BaseService baseService;
    private PurPInventoryDao purPInventoryDao;
    private List<PChangeImportExportLogModel> errorInfoList = new ArrayList<>();
    private TWarehouseInfoDao tWarehouseInfoDao;
    private TProjectDao tProjectDao;
    private BoardService boardService;
    private Date appDate;

    public PInvProListener(PurInvProDao purInvProDao,
                           BoardDao boardDao,
                           ImportCallBack callBack,
                           LogService logService,
                           BaseService baseService,
                           PurPInventoryDao purPInventoryDao,
                           TWarehouseInfoDao tWarehouseInfoDao,
                           TProjectDao tProjectDao,
                           PurChangeDao purChangeDao,
                           BoardService boardService
    ) {
        this.purChangeDao = purChangeDao;
        this.boardDao = boardDao;
        this.callBack = callBack;
        this.logService = logService;
        this.baseService = baseService;
        this.purPInventoryDao = purPInventoryDao;
        this.tWarehouseInfoDao = tWarehouseInfoDao;
        this.tProjectDao = tProjectDao;
        this.purInvProDao = purInvProDao;
        this.boardService=boardService;
        appDate = new Date();
    }

    @Override
    public void invoke(PChangeOrderExcelModel data, AnalysisContext analysisContext) {
        String errorInfo = "";
        //开始进行常规验证
        if (null == data.getCeoUseItyId() || data.getCeoUseItyId().equals("")) {
            errorInfo += "【库存ID（禁改）】列不可为空也不可为0，请您修改！" + "\r\n";
        } else {
            try {
                Integer ceoUseItyId = Integer.valueOf(data.getCeoUseItyId());
                if (purChangeDao.getInventoryPrimaryKey(ceoUseItyId) == null) {
                    errorInfo += "【库存ID（禁改）】列ID不可修改！" + "\r\n";
                }
            } catch (Exception e) {
                errorInfo += "【库存ID（禁改）】列ID不可修改！" + "\r\n";
            }
        }

        if (null == data.getCeoNeedProCode() || data.getCeoNeedProCode().equals("")) {
            errorInfo += "【提报计划项目编号】列不可为空也不可不填，请您修改！" + "\r\n";
        } else if (getVWProjectByCode(data.getCeoNeedProCode()) == null) {
            errorInfo += "【提报计划项目编号】列项目编号不存在，请您修改！" + "\r\n";
        }
//        else if(purInvProDao.getTCostByCode(data.getCeoNeedProCode())!=null){
//            errorInfo += "【提报计划项目编号】列项目编号是成本中心项目，不可以库存划项目，请您修改！" + "\r\n";
//        }
        if (null == data.getCeoNeedProName() || data.getCeoNeedProName().equals("")) {
            errorInfo += "【提报计划项目名称】列不可为空也不可不填，请您修改！" + "\r\n";
        }

        if (null == data.getCeoNeedMatName() || data.getCeoNeedMatName().equals("")) {
            errorInfo += "【提报计划物料描述】列不可为空也不可不填，请您修改！" + "\r\n";
        } else if (data.getCeoNeedMatName().length() > 1000) {
            errorInfo += "【提报计划物料描述】列项内容过多，请保持所有字符在1000个以内，包括回车，请您修改！" + "\r\n";
        }

        if (null == data.getCeoNeedNum() || data.getCeoNeedNum().equals("")) {
            errorInfo += "【提报计划数量】列不可为空也不可不填，请您修改！" + "\r\n";
        } else {
            try {
                Double ceoNeedNum = Double.valueOf(data.getCeoNeedNum());
                if (ceoNeedNum <= 0) {
                    errorInfo += "【提报计划数量】列的数字必须大于0，请您修改！" + "\r\n";
                }
            } catch (Exception e) {
                errorInfo += "【提报计划数量】列只能是数字，请修改！" + "\r\n";
            }

        }


        if (null != data.getCeoRemark() && !data.getCeoRemark().equals("")) {
            if (data.getCeoRemark().length() > 255) {
                errorInfo += "【备注】列项内容过多，请保持所有字符在255个以内，包括回车，请您修改！" + "\r\n";
            }
        }
        if (null != data.getCeoNeedStandardNo()) {
            if (data.getCeoNeedStandardNo().length() > 255) {
                errorInfo += "【项目号】列项内容过多，请保持所有字符在255个以内，包括回车，请您修改！" + "\r\n";
            }
        }
        PInventory pInventory = null;
        if (null != data.getCeoUseItyId()) {
            try {
                pInventory = purChangeDao.getInventoryPrimaryKey(Integer.valueOf(data.getCeoUseItyId()));
            } catch (NumberFormatException e) {
                errorInfo += "ID禁改列被删除或ID不存在，请您修改！" + "\r\n";
            }
            if (pInventory == null) {
                errorInfo += "ID禁改列被删除或ID不存在，请您修改！" + "\r\n";
            } else if (pInventory.getItyStockType().equals(2)) {
                errorInfo += "该物料是在库类型是项目在库，无法库存划项目，请修改！" + "\r\n";
            }
        }
        if (null != data.getCeoUseItyId()) {
            PInventoryModel pInventoryModel = null;
            try {
                pInventoryModel = purPInventoryDao.getInventoryModelByPrimaryKey(data.getCeoUseItyId());
            } catch (Exception e) {
                errorInfo += "ID禁改列被删除或ID不存在，请您修改！" + "\r\n";
            }
            if (pInventoryModel == null) {
                errorInfo += "ID禁改列被删除或ID不存在，请您修改！" + "\r\n";
            } else {
                if (pInventoryModel.getItyAvaNum() <= 0 || pInventoryModel.getItyNum() <=0) {
                    errorInfo += "所选库存可用数量不足，请您修改！" + "\r\n";
                } else {
                    try {
                        if (BigDecimalUtils.div(pInventoryModel.getItyAvaNum(), Double.valueOf(data.getCeoNeedNum()), 3) < 1) {
                            errorInfo += "所选库存可用数量不足，请您修改！" + "\r\n";
                        }
                    } catch (Exception e) {
                        errorInfo += "【提报计划数量】列只能是数字，请修改！" + "\r\n";
                    }
                }
            }
        }else {
            errorInfo += "ID禁改列被删除或ID不存在，请您修改！" + "\r\n";
        }
        if (!errorInfo.equals("") && null != pInventory) {
            //根据主键获取库存信息
            PChangeImportExportLogModel model = new PChangeImportExportLogModel();
            model.setCeoUseItyId(pInventory.getItyId().toString());
            model.setCeoUseProCode(pInventory.getItyProCode());
            model.setCeoUseProName(pInventory.getItyProName());
            model.setCeoUseMatName(pInventory.getItyMatDesc());
            model.setCeoUseNum(data.getCeoUseNum());
            model.setCeoUseWhiName(tWarehouseInfoDao.selectByPrimaryKey(pInventory.getItyWhiId()).getWhiName());
            model.setCeoUsePosition(pInventory.getItyPosition());
            model.setCeoUseItyStockType((pInventory.getItyStockType() == 1 ? "库存在库" : "项目在库"));
            model.setCeoTrackCode(pInventory.getItyTrackCode());
            String ceoNeedProCode = boardService.projectCodeHandle(data.getCeoNeedProCode());
            model.setCeoNeedProCode(ceoNeedProCode);
            model.setCeoNeedProName(data.getCeoNeedProName());
            model.setCeoNeedMatName(data.getCeoNeedMatName());
            model.setCeoNeedNum(data.getCeoNeedNum());
            model.setCeoRemark(data.getCeoRemark());
            model.setCeoAppPersonId(ShiroUtils.getUserId());
            model.setCeoAppDate(appDate);
            //导入导出类别
            model.setCeoType(1);
            model.setCeoWarnInfo(errorInfo);
            model.setCeoStatus(1);
            model.setCeoNeedStandardNo(data.getCeoNeedStandardNo());
            errorInfoList.add(model);
        } else if (!errorInfo.equals("") && null == pInventory) {
            //根据主键获取库存信息
            PChangeImportExportLogModel model = new PChangeImportExportLogModel();
            model.setCeoUseItyId(data.getCeoUseItyId());
            model.setCeoUseProCode(data.getCeoUseProCode());
            model.setCeoUseProName(data.getCeoUseProName());
            model.setCeoUseMatName(data.getCeoUseMatName());
            model.setCeoUseNum(data.getCeoUseNum());
            model.setCeoUseWhiName(data.getCeoUseWhiName());
            model.setCeoUsePosition(data.getCeoUsePosition());
            model.setCeoUseItyStockType(data.getCeoUseItyStockType());
            model.setCeoTrackCode(data.getCeoTrackCode());
            String ceoNeedProCode = boardService.projectCodeHandle(data.getCeoNeedProCode());
            model.setCeoNeedProCode(ceoNeedProCode);
            model.setCeoNeedProName(data.getCeoNeedProName());
            model.setCeoNeedMatName(data.getCeoNeedMatName());
            model.setCeoNeedNum(data.getCeoNeedNum());
            model.setCeoRemark(data.getCeoRemark());
            model.setCeoAppPersonId(ShiroUtils.getUserId());
            model.setCeoAppDate(appDate);
            //导入导出类别
            model.setCeoType(1);
            model.setCeoWarnInfo(errorInfo);
            model.setCeoStatus(1);
            model.setCeoNeedStandardNo(data.getCeoNeedStandardNo());
            errorInfoList.add(model);
        } else {
            try {
                //根据主键获取库存信息
                PInventory ceoUsePInventory = purChangeDao.getInventoryPrimaryKey(Integer.valueOf(data.getCeoUseItyId()));
                PInventoryProjectMarkModel param = new PInventoryProjectMarkModel();
                param.setIpmBeforeItyId(ceoUsePInventory.getItyId());
                param.setIpmNum(new BigDecimal(data.getCeoNeedNum()).doubleValue());
                param.setIpmItyType("p");
                param.setIpmStandardNo(data.getCeoNeedStandardNo());
                String ceoNeedProCode = boardService.projectCodeHandle(data.getCeoNeedProCode());
                param.setIpmInProjectCode(ceoNeedProCode);
                param.setIpmInProjectName(data.getCeoNeedProName());
                param.setIpmMatCode(ceoUsePInventory.getItySapCode());
                param.setIpmMatDesc(data.getCeoNeedMatName());
                param.setIpmAppStatus(1);
                param.setIpmProposerId(ShiroUtils.getUser().getId());
                param.setIpmDate(appDate);
                param.setIpmRemark(data.getCeoRemark());
                if (param.getIpmId() == null || param.getIpmId() == 0) {
                    //更改库存可用数量
                    ceoUsePInventory.setItyAvaNum(ceoUsePInventory.getItyAvaNum() - param.getIpmNum());
                    purPInventoryDao.updateItyAvaNumByPrimary(ceoUsePInventory);
                    purInvProDao.insertSelective(param);
                }
                logService.saveLog("【外购件】保存库存化项目标记", "保存的标记的库存物料描述：" + ceoUsePInventory.getItyMatDesc());
            } catch (Exception e) {
                e.printStackTrace();

            }
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        if (errorInfoList.size() > 0) {
            callBack.onWarning(errorInfoList);
        } else {
            callBack.onSuccess();
        }
    }


    @Override
    public void onException(Exception exception, AnalysisContext context) {

    }


}